const mongoose = require("mongoose");

const Schema = mongoose.Schema;

const db = mongoose.connection;

const PackData = new Schema({
  _id: Number,
  accountName: String,
  passWord: String,
  online: Boolean,
});
const Pack = mongoose.model("user", PackData);
function initConnect() {
  return new Promise((resolve, reject) => {
    mongoose.connect("mongodb://127.0.0.1:27017/SSRProjectData", {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });
    db.on("open", () => console.log("数据库连接成功"));
    db.on("disconnected", () => console.log("数据库连接已断开"));
  });
}

function save(t) {
  return new Promise((resolve, reject) => {
    t.save({}, function (err, data) {
      resolve(err ? err : data);
    });
  });
}

function find(rules) {
  if (!rules) {
    rules = {};
  } else {
    let str = rules;
    rules = {};
    let sign = str.match(/(>)|(<)|(===)/g)[0];
    sign = str.match(/(>=)|(<=)/g) ? str.match(/(>=)|(<=)/g)[0] : sign;
    let target = str.split(sign)[0];
    let value = str.split(sign)[1];
    switch (sign) {
      case "<":
        rules[target] = { $lt: value };
        break;
      case ">":
        rules[target] = { $gt: value };
        break;
      case "<=":
        rules[target] = { $lte: value };
        break;
      case ">=":
        rules[target] = { $gte: value };
        break;
      case "===":
        rules[target] = value;
        break;
    }
  }
  return new Promise((resolve, reject) => {
    Pack.find(rules, (err, data) => {
      resolve(err ? err : data);
    });
  });
}
function updata(rules, option) {
  return new Promise((resolve, reject) => {
    Pack.updateOne(rules, option, (err, data) => {
      resolve(err ? err : data);
    });
  });
}
function removeData(rules) {
  return new Promise((resolve, reject) => {
    Pack.deleteOne(rules, () => resolve(find()));
  });
}

module.exports = {
  Pack,
  removeData,
  updata,
  find,
  save,
  initConnect,
};
